package com.zcxx.cotton.mobile;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.AppConstant;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.http.SendUtils;
import com.zcxx.cotton.base.domain.PubPickerDevice;
import com.zcxx.cotton.base.service.IPubPickerDeviceService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import com.zcxx.cotton.mobile.vo.AppPickInfoSumVO;
import com.zcxx.cotton.mobile.vo.AppPickerSumVO;
import com.zcxx.cotton.mobile.vo.AppUserVO;
import com.zcxx.cotton.pick.domain.PickInfo;
import com.zcxx.cotton.pick.domain.PickMapInfo;
import com.zcxx.cotton.pick.service.IPickInfoService;
import com.zcxx.cotton.pick.service.IPickMapInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Api(tags = "移动端接口")
@RequestMapping()
public class AppCommonController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IPickInfoService pickInfoService;

    @Autowired
    private IPickMapInfoService pickMapInfoService;

    @Autowired
    private IPubPickerDeviceService pubPickerDeviceService;

    @Autowired
    private SendUtils sendUtils;


    @PostMapping("/mobile/loginWx")
    @ApiOperation("微信登录")
    public AjaxResult loginWx (LoginBody loginBody)
    {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),0,false);

        SysUser sysUser = userService.selectUserByUserName(loginBody.getUsername());
        JSONObject object = new JSONObject();
        object.put("JSESSIONID", token);
        object.put("userId", sysUser.getUserId());
        object.put("deptId", sysUser.getDeptId());

        return AjaxResult.success(object);
    }

    @PostMapping("/app/getUser")
    @ApiOperation("获取用户信息")
    public AjaxResult getUserInfo()
    {
        LoginUser loginUser = getLoginUser();
        if (loginUser != null)
        {
            AppUserVO appUserVo = new AppUserVO();
            SysUser user = loginUser.getUser();
            appUserVo.setUserName(loginUser.getUsername());
            appUserVo.setDeptId(loginUser.getDeptId());
            appUserVo.setDeptName(user.getDept().getDeptName());

            appUserVo.setTel(loginUser.getUser().getPhonenumber());

            return AjaxResult.success(appUserVo);
        }

        return AjaxResult.success();
    }

    @GetMapping("/mobile/getAppSecret")
    @ApiOperation("获取秘钥")
    public AjaxResult getAppSecret()
    {
        return AjaxResult.success(AppConstant.APP_SECRET);
    }


    @PostMapping("/app/wechat/getPickerList")
    @ApiOperation("获取采棉机列表")
    public TableDataInfo getPickerList(Long deptId ,String deviceName ,String deptName)
    {
        PubPickerDevice pickerDevice = new PubPickerDevice();
        pickerDevice.setDeptId(deptId);
        pickerDevice.setName(deviceName);
        pickerDevice.setRegion(deptName);
        startPage();
        List<PubPickerDevice> deviceList = pubPickerDeviceService.selectPubPickerDeviceList(pickerDevice);
        return getDataTable(deviceList);
    }

    @PostMapping("/app/wechat/getPickerListNew")
    @ApiOperation("获取采棉机列表")
    public TableDataInfo getPickerListNew(Long deptId, String status, String deviceName ,String deptName)
    {
        PubPickerDevice pickerDevice = new PubPickerDevice();
        pickerDevice.setDeptId(deptId);
        pickerDevice.setStatus(status);
        pickerDevice.setName(deviceName);
        pickerDevice.setRegion(deptName);
        startPage();
        List<PubPickerDevice> deviceList = pubPickerDeviceService.selectPubPickerDeviceList(pickerDevice);
        return getDataTable(deviceList);
    }


    @PostMapping("/app/wechat/getPickerSum")
    @ApiOperation("采棉机在线统计")
    public AjaxResult getPickerSum()
    {
        List<PubPickerDevice> deviceList = pubPickerDeviceService.list();
        int all = deviceList.size();
        int online = (int)deviceList.stream().filter(device -> "0".equals(device.getStatus())).count();
        int off = all - online;
        AppPickerSumVO appPickerSumVo = new AppPickerSumVO();
        appPickerSumVo.setAll(all);
        appPickerSumVo.setOnline(online);
        appPickerSumVo.setOff(off);
        return AjaxResult.success(appPickerSumVo);
    }


    @PostMapping("/app/wechat/getPickInfoList")
    @ApiOperation("获取采摘信息")
    public TableDataInfo getPickInfoList(String deviceMainCode, String startTime, String endTime,String pianqu)
    {
        PickInfo pickInfo = new PickInfo();
        pickInfo.setDeviceMainCode(deviceMainCode);
        pickInfo.setPianqu(pianqu);
        pickInfo.setBeginBillDate(startTime);
        pickInfo.setEndBillDate(endTime);
        startPage();
        List<PickInfo> pickInfos = pickInfoService.selectPickInfoList(pickInfo);
        return getDataTable(pickInfos);
    }


    @PostMapping("/app/wechat/getPickInfoSum")
    @ApiOperation("获取采摘统计")
    public AjaxResult getPickInfoSum(Long deptId, String startTime, String endTime)
    {
        PickInfo pickInfo = new PickInfo();
        pickInfo.setDeptId(deptId);
        pickInfo.setBeginBillDate(startTime);
        pickInfo.setEndBillDate(endTime);
        List<PickInfo> pickInfos = pickInfoService.selectPickInfoList(pickInfo);

        Map<String, List<PickInfo>> pickInfoMap = pickInfos.stream()
                .collect(Collectors.groupingBy(PickInfo::getDeviceMainCode));
        int yearTotal = 0;

        JSONArray array = new JSONArray();
        Set<String> strings = pickInfoMap.keySet();
        for (String string : strings) {
            PubPickerDevice pickerDevice = pubPickerDeviceService.selectPubPickerDeviceById(string);
            List<PickInfo> infoList = pickInfoMap.get(string);
            JSONObject object = new JSONObject();
            object.put("deviceMainCode", string);
            object.put("deviceName", pickerDevice.getName());
            object.put("number", infoList.size());
            object.put("carNo", pickerDevice.getCarNo());
            yearTotal += infoList.size();

            array.add(object);
        }

        AppPickInfoSumVO appPickInfoSumVo = new AppPickInfoSumVO();
        appPickInfoSumVo.setYearTotal(yearTotal);
        appPickInfoSumVo.setTotal(array.size());
        appPickInfoSumVo.setList(array);

        return AjaxResult.success(appPickInfoSumVo);
    }


    @PostMapping("/app/wechat/getPickMapList")
    @ApiOperation("采棉机轨迹")
    public TableDataInfo getPickMapList(String deviceMainCode, String startTime, String endTime)
    {
        PickMapInfo pickMapInfo = new PickMapInfo();
        pickMapInfo.setDeviceMainCode(deviceMainCode);
        pickMapInfo.setBeginMapTime(startTime);
        pickMapInfo.setEndMapTime(endTime);

//        startPage();
        List<PickMapInfo> mapInfos = pickMapInfoService.selectPickMapInfoList(pickMapInfo);
        return getDataTable(mapInfos);
    }


    @PostMapping("/app/wechat/getPlantInfoByidCode")
    @ApiOperation("获取地块信息")
    public AjaxResult getPickInfoCount(String idCode)
    {

        String url = "https://zs.ecottone.com/api/getPlantInfoByidCode";
        Map<String, String> params = new HashMap<>();
        params.put("idCode", idCode);
        params.put("key", "ByidCode");
        String s = sendUtils.sendPost(url, params);
        JSONObject parse = JSONObject.parse(s);
        JSONObject data = parse.getJSONObject("data");
        JSONArray array = data.getJSONArray("data");
        if (data.getString("code").equals("200")){
            return AjaxResult.success(data.getString("msg"),array);
        }else {
            return AjaxResult.error(data.getString("msg"));
        }
    }


    /**
        棉包补录/破损上报
     */
    @PostMapping("/app/wechat/reportPickInfo")
    @ApiOperation("棉包补录/破损上报")
    public AjaxResult reportPickInfo(ReportPickInfoDTO reportPickInfoDTO)
    {
        JSONObject object = new JSONObject();
        object.put("deviceMainCode", reportPickInfoDTO.getDeviceMainCode());
        object.put("sampleNumber", reportPickInfoDTO.getSampleNumber());
        object.put("farmerName", reportPickInfoDTO.getFarmerName());
        object.put("farmerIc", reportPickInfoDTO.getFarmerIc());
        object.put("longitude", reportPickInfoDTO.getLongitude());
        object.put("latitude", reportPickInfoDTO.getLatitude());
        object.put("traceNo", reportPickInfoDTO.getTraceNo());
        object.put("dataType", reportPickInfoDTO.getDataType());
        object.put("plantAddress", reportPickInfoDTO.getPlantAddress());
        String url = "https://zs.ecottone.com/api/createPickInfo";
        String s = sendUtils.sendPost(url, object);
        JSONObject parse = JSONObject.parse(s);
        if (!parse.getString("code").equals("0")){
            return AjaxResult.error(parse.getString("msg"));
        }else {
            return AjaxResult.success(parse.getString("msg"));
        }

    }
    @PostMapping("/app/wechat/getPickInfoSumByPianqu")
    @ApiOperation("获取采摘用片区统计")
    public AjaxResult getPickInfoSumByPianqu(Long deptId, String startTime, String endTime)
    {
        PickInfo pickInfo = new PickInfo();
        pickInfo.setDeptId(deptId);
        pickInfo.setBeginBillDate(startTime);
        pickInfo.setEndBillDate(endTime);
        List<PickInfo> pickInfos = pickInfoService.selectPickInfoList(pickInfo);

        Map<String, List<PickInfo>> pickInfoMap = pickInfos.stream()
                .collect(Collectors.groupingBy(PickInfo::getPianqu));
        int yearTotal = 0;

        JSONArray array = new JSONArray();
        Set<String> strings = pickInfoMap.keySet();
        for (String string : strings) {
            List<PickInfo> infoList = pickInfoMap.get(string);
            JSONObject object = new JSONObject();
            object.put("pianqu", string);
            object.put("number", infoList.size());
            yearTotal += infoList.size();

            array.add(object);
        }

        AppPickInfoSumVO appPickInfoSumVo = new AppPickInfoSumVO();
        appPickInfoSumVo.setYearTotal(yearTotal);
        appPickInfoSumVo.setTotal(array.size());
        appPickInfoSumVo.setList(array);

        return AjaxResult.success(appPickInfoSumVo);
    }
}
